<template>
  <div class="government">
    <div class="view"></div>
    <Header></Header>
    <MainMap @historyMethod="historyMethod" @toggleTab="toggleTab"></MainMap>
    <div class="borderBg"></div>
  </div>
</template>
<style lang="scss" scoped>
  #governmentMap {
    width: 100vw;
    height: 100vh;
  }
  .view {
    width: 100vw;
    height: 100vh;
    background: url('/img/bg-home.png') no-repeat;
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
    z-index: 1;
  }
  .borderBg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('/img/bg-border.png') no-repeat;
    background-size: 100.2% 99.5%;
    pointer-events: none;
    z-index: 2;
  }
</style>
<script setup>
  import { onMounted, provide, inject, ref, nextTick, onUnmounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import Header from '@/components/header.vue'
  import MainMap from '@/components/home/MainMap.vue'
  import mqtt from 'mqtt/dist/mqtt'
  import { useCompanyInfoStore } from '../stores/platform'
  import { useDroneStore } from '@/stores/mqttInfo'
  import { gcj02towgs84 } from '@/utils/coordTransform.js'
  const companyInfoStore = useCompanyInfoStore()
  const droneStore = useDroneStore()
  const router = useRouter()
  //底部menu Id
  const footerId = ref()
  provide('footerId', footerId)
  const playAudio = inject('playAudio')
  const message = inject('$message')

  //  配置MQTT
  let client = null // 实例
  let topic = '/company-id' // 主题
  let options = {
    clientId: 'jnksClientId20220601-mqtt' + Math.random(), //clientId 加随机数可解决诡异重连
    // username: 'admin', // 用户名
    // password: 'syadmin2589', // 密码
    username: 'front-end', // 用户名
    password: '123456', // 密码
  }
  // mqtt 连接地址
  let mqttUrl = import.meta.env.VITE_BASE_MQTT
  let ipt = '/company'
  let currentDroneId = [] // 当前无人机id 数组
  let realtimeData = [] // 当前无人机数据 数组
  /**
   * @description: mqtt 链接
   */
  const mqttMsg = () => {
    if (!client) {
      client = mqtt.connect(mqttUrl, options)
    }
    // mqtt连接
    client.on('connect', (e) => {
      // topic 订阅的主题
      // QoS0 代表，Sender 发送的一条消息，Receiver 最多能收到一次，也就是说 Sender 尽力向 Receiver 发送消息，如果发送失败，也就算了；
      // QoS1 代表，Sender 发送的一条消息，Receiver 至少能收到一次，也就是说 Sender 向 Receiver 发送消息，如果发送失败，会继续重试，直到 Receiver 收到消息为止，但是因为重传的原因，Receiver 有可能会收到重复的消息；
      // QoS2 代表，Sender 发送的一条消息，Receiver 确保能收到而且只收到一次，也就是说 Sender 尽力向 Receiver 发送消息，如果发送失败，会继续重试，直到 Receiver 收到消息为止，同时保证 Receiver 不会因为消息重传而收到重复的消息

      client.subscribe(topic, { qos: 0 }, (error) => {
        if (!error) {
          // 消息订阅成功
          console.log('消息订阅成功')
        } else {
          // 消息订阅失败
        }
      })
    })
    // 接收消息处理
    client.on('message', (topic, msg) => {
      // message 接受到的消息 二进制 需要 toString 转格式
      let mqMsg = msg.toString()
      console.log('mqMsg>>>>>>>>>', mqMsg)
      if (mqMsg.split('=')[1] == 1) {
        let mpttobj = JSON.parse(JSON.parse(mqMsg.split('=')[0]).data)
        let tudeArr = gcj02towgs84(mpttobj.curLongitude, mpttobj.curLatitude)
        mpttobj.curLongitude = tudeArr[0]
        mpttobj.curLatitude = tudeArr[1]
        mpttobj.driverLongitude = mpttobj.gpsDriverLongitude
        mpttobj.driverLatitude = mpttobj.gpsDriverLatitude
        let str = {
          data: JSON.stringify(mpttobj),
          topic: '/zone-28737',
          type: '1',
        }
        mqMsg = JSON.stringify(str) + '=1'
      }
      console.log('改变的mqMsg', mqMsg)
      droneStore.setDroneDate(mqMsg)
      let info = mqMsg.split('=')[0]
      let type = mqMsg.split('=')[1]
      let flydata = info.trim()
      console.log('flydata')
      // 非空
      if (flydata != '') {
        if (type == 1) {
          // 无人机起飞
          // json字符串转对象
          flydata = JSON.parse(flydata)
          if (flydata.data) {
            flydata = JSON.parse(flydata.data)
          }
          if (flydata) {
            // 判断无人机id 是否存在
            if (currentDroneId.indexOf(flydata.droneCode) == -1) {
              //存储新无人机起飞标识
              if (flydata.type != 7) {
                flicker()
                playAudio() // 语音播报
                droneStore.setnewfly()
              }
              currentDroneId.push(flydata.droneCode)
              localStorage.setItem('currentDroneId', JSON.stringify(currentDroneId))
              droneStore.setUavflynowdata(currentDroneId)
              // 判断是否有音频文件地址
              // if (flydata.audioPathSwat != '') {
              //   setTimeout(() => {
              //     playAudio(flydata.audioPathSwat) // 语音播报
              //   }, 3 * 1000)
              // }
              // 接受无人机轨迹信息时 增加 当前时间字段 用来判断无人机的最后更新时间
              flydata.lastTime = +new Date()
              realtimeData.push(flydata)
            }
          }
        } else if (type == 2) {
          // 无人机降落
          var num = JSON.parse(flydata).data.split('-')[0]
          let flycompanvuecun = []
          let droneId = []
          let model = ''
          let type = ''
          realtimeData.forEach((item) => {
            if (item.droneCode != num) {
              flycompanvuecun.push(item)
            } else {
              model = item.model ? item.model : ''
              type = item.type
            }
          })
          currentDroneId.map((j) => {
            if (j != num) {
              droneId.push(j)
            }
          })
          nextTick(() => {
            if (type != 7) {
              message({
                message: model + '无人机已降落',
                type: 'success',
              })
            }

            realtimeData = flycompanvuecun
            currentDroneId = droneId
            localStorage.setItem('currentDroneId', JSON.stringify(currentDroneId))
          })
        } else if (type == 11) {
          // 自动预案
          droneStore.newonpenDevicestate()
        }
      }
    })

    // 断开发起重连
    client.on('reconnect', (error) => {
      // error
    })
    // 链接异常处理
    client.on('error', (error) => {
      //  error
    })
  }
  /**
   * @description:  闪红屏
   */
  const flicker = () => {
    // accuNumber() //手动累加告警数量
    if (document.getElementById('light')) {
      document.getElementById('entry').removeChild(document.getElementById('light'))
    }
    const div = document.createElement('div')
    div.id = 'light'
    document.getElementById('entry').appendChild(div)
    setTimeout(() => {
      if (document.getElementById('light')) {
        document.getElementById('entry').removeChild(document.getElementById('light'))
      }
    }, 12000)
  }

  const storageNum = ref(null) //缓存告警数量
  const accuNumber = () => {
    //获取缓存告警数量
    storageNum.value = JSON.parse(companyInfoStore.alarmNumState.alarmNum)
    Object.keys(storageNum.value).forEach((key) => {
      storageNum.value[key] = Number(storageNum.value[key]) + 1
    })
    companyInfoStore.setAlarmNum(JSON.stringify(storageNum.value))
  }
  //历史回放按钮
  let footer = ref()
  const historyMethod = () => {
    footer.value.historyMethod()
  }
  //切换底部tab事件
  const toggleTab = () => {
    footer.value.toggleTab(1, 0, true)
  }
  onMounted(() => {
    let token = localStorage.getItem('companytoken')
    if (token == null || token == undefined || token.length < 3) {
      router.push('/login')
    }
    mqttMsg()
    currentDroneId = JSON.parse(localStorage.getItem('currentDroneId'))
      ? JSON.parse(localStorage.getItem('currentDroneId'))
      : []
    // topic = ipt + '-' + companyInfoStore.state.companyInfo.companyId
    topic = '/zone-28737'
  })
  onUnmounted(() => {
    if (client) {
      client.end() //离开页面的时候  关闭mqtt连接
      client = null
    }
  })
</script>
<style>
  #light {
    position: absolute;
    pointer-events: none;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100vw;
    z-index: 10000;
    background: transparent;
    animation: light-animate 600ms ease-out 20 alternate;
  }

  .confirmadd_el-select-dropdown {
    border: transparent !important;
    background-color: rgba(35, 62, 92, 1);
    color: #fff;
    /* // width: 50% !important;
    // min-width: 0px !important; */

    .el-select-dropdown__item {
      font-size: 14px;
      cursor: pointer;
      color: #fff;
    }
    .el-select .el-input__wrapper,
    .el-input__wrapper {
      background-color: rgba(35, 62, 92, 1);
      color: #fff;
      border: 1px solid #00f3fd;
      box-shadow: none;
    }

    .el-select-dropdown__item.hover,
    .el-select-dropdown__item:hover {
      background-color: #2daef1;
    }
    /* .el-select-dropdown__wrap {
      max-height: 150px !important;
    } */
    .el-select-dropdown__item.is-hovering {
      background-color: #1f5a9e;
    }
  }
  .confirmadd_el-select-dropdown[data-popper-placement^='bottom'] .el-popper__arrow::before {
    border-bottom-color: rgb(35, 62, 92) !important;
    border-right-color: rgb(35, 62, 92) !important;
    border-top-color: rgb(35, 62, 92) !important;
    border-left-color: rgb(35, 62, 92) !important;
    background: rgb(35, 62, 92);
  }

  @keyframes light-animate {
    0% {
      box-shadow: inset 0 0 200px rgba(255, 0, 0, 0.8), inset 0 0 200px rgba(255, 0, 0, 0.6);
    }
    50% {
      box-shadow: inset 0 0 100px rgba(255, 0, 0, 0.8), inset 0 0 100px rgba(255, 0, 0, 0.6);
    }
    100% {
      box-shadow: inset 0 0 200px rgba(255, 0, 0, 0.9), inset 0 0 200px rgba(255, 0, 0, 0.7);
    }
  }
</style>
